using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace CoreMobile.net
{
    public class Client  : NetObject
    {

        private static Queue<string> msgs=new Queue<string>();
        public static string status = "Listo para mandar";

        public static bool sendQuickly(string _msg)
        {
            //MessageBox.Show(_msg);
            //return true;

            msgs.Enqueue(_msg);

            while (msgs.Count > 0)
            {


            Client client = new Client(DEFAULT_IP,DEFAULT_SEND_PORT);
            try
            {
                client.connect();
            }catch(Exception e)
            {
                status = e.Message;
                return false;
            }
                string confirmation;

               try{confirmation = client.sendAndReceive(msgs.Peek());}catch(Exception e)
               {
                   status = e.Message;
                   client.disconnect();
                   return false;
               }
                if(confirmation.Trim() == "OK")
                    msgs.Dequeue();
                else
                {
                    status = "No se recibio conf.";
                    client.disconnect();
                    return false;
                }

            try
            {
                client.disconnect();
            }catch(Exception e)
            {
                status = e.Message;
                return false;
            }

            }

            status = "Listo para enviar";
            return true;
        }

        //private NetworkStream networkStream;
        //private TcpClient socketClient;
        
        private string errorMsg = null;

        private IPEndPoint ipep;
        //private IPEndPoint ipep2;

        private Socket server;
        //private Socket server2;

        public Client(string ip, int port) : base(ip, port, LowLevelProtocol.TCP)
        {
            
             ipep = new IPEndPoint(
                        IPAddress.Parse(ip), port);

             server = new Socket(AddressFamily.InterNetwork,
                           SocketType.Stream, ProtocolType.Tcp);

             /*ipep2 = new IPEndPoint(
                         IPAddress.Parse(ip), port+1);

             server2 = new Socket(AddressFamily.InterNetwork,
                           SocketType.Stream, ProtocolType.Tcp);*/
        }
        
        
        public string ErrorMsg
        {
            get { return errorMsg; }
        }

        public bool connect() 
        {

              //  this.socketClient = new TcpClient(this.Ip, this.Port);
              // networkStream = this.socketClient.GetStream();


            server.Connect(ipep);
            //server2.Connect(ipep2);
           return true;
        }


        public string sendAndReceive(string dataToSend)
        {
            byte[] data = new byte[1024];
            string stringData;


            this.send(dataToSend);
            
            /*StreamReader reader = new StreamReader(networkStream);
            string line = reader.ReadToEnd();
            reader.Close();
            return line;*/

            //return "<no-receive>";

            data = new byte[1024];
            var recv = server.Receive(data);
            stringData = Encoding.UTF8.GetString(data, 0, recv);
            
            return stringData;
            //return HttpUtility.UrlDecode(con, System.Text.Encoding.UTF8); ;
            //return this.ReadMessage(server2);
        }


        public void send(string dataToSend)
        {

            //int recv = server.Receive(data); //ecco
            //stringData = Encoding.ASCII.GetString(data, 0, recv);

            //MessageBox.Show("s: " + dataToSend);
            //server.Send(Encoding.UTF8.GetBytes("<nil>"));
            int bytesSent = server.Send(Encoding.UTF8.GetBytes(dataToSend));

            //server.Receive()

           /* StreamWriter writer = new StreamWriter(networkStream);
            writer.Write("<nil>");
            writer.Write(dataToSend);
            writer.Flush();
            writer.Close();*/
        }

        public bool disconnect()
        {

           // networkStream.Close();
           // this.socketClient.Close();

           server.Close();
        //        server2.Close();

            return true;
        }


    }
}